import React from 'react';
import { Breadcrumb, Icon, Button, Table, Modal, Input, Select, Pagination, message ,Row,Col,DatePicker,Form,Checkbox,AutoComplete,InputNumber,Upload } from 'antd';
import $ from 'jquery';
import Config from '../../common/config';
import noRepeat from '../commonFunction/noRepeat';
import getFormatDate from '../commonFunction/getFormatData';
import moment from 'moment';
const config = new Config();
const { RangePicker } = DatePicker;
const { TextArea } = Input;
const FormItem = Form.Item;
const Option = Select.Option;
const userInfo = JSON.parse(sessionStorage.getItem('UserInfo')); //用户信息
const root = userInfo.root;

class FileManage1 extends React.Component {
    constructor(props) {
        super(props);
        this.state = {
            createpeople:'',//创建人
            visible: false,//我的申请模态框
            dateStr:['',''],//默认今天的日期字符串
            date:[undefined,undefined],//默认今天的日期
            dateStr1:['',''],//默认今天的日期字符串
            date1:['',''],//默认今天的日期
            channelList: [],//申请列表
            channelcount: 0,//申请列表条数
            pageindex:1,//当前页码
            wordCount1:0,//申请事宜字数
            selectedRows:[],//打印选中的列表
            selectionList:[[],[],[],[]],//筛选列表
            matchProducts:[],//产品自动完成列表
            matchProducts1:[],//平台自动完成列表
            selectValue:'',//产品自动完成列表选中的值
            selectValue1:'',//平台自动完成列表选中的值
            authTreeOfOne:{},//小工具权限
            record:{},//
            channelList2:[{}],
            userList:{},//用户列表
        }
    }
    componentWillMount(){
        console.log(userInfo.auth);
        if(userInfo.auth){
            if(userInfo.auth['橘色小工具']){
                this.setState({
                    authTreeOfOne:userInfo.auth['橘色小工具']
                })
            }
        }
    }
    componentDidMount() {
        this.getBannerList();
    }
    //保存
    saveBanner() {
        this.props.form.validateFields((err, values)=>{
            if(!err){
                const {BannerId} = this.state;
                console.log(values);
                let url,
                    data={
                        inforname:values.inforname,//收款账户名
                        openingbank:values.openingbank,//开户行
                        subbranch:values.subbranch,//支行
                        account:values.account,//银行卡号
                    };
                if(BannerId){
                    url = `${config.juseLittleTool}/information/update`;
                    data.id = BannerId;
                }else{
                    url = `${config.juseLittleTool}/information/save`;
                }
                $.ajax({
                    url: url,
                    type: "post",
                    async: true,
                    headers: {
                        'Authorization': 'Bearer ' + sessionStorage.getItem('token'),
                    },
                    data:data,
                    success: data => {
                        console.log(data);
                        if(data.code === 200){
                            this.setState({
                                visible: false,
                            },()=>{
                                this.getBannerList()
                            });
                            this.props.form.resetFields();
                        }else{
                            if(data.code===201){
                                this.props.form.setFields({
                                    account: { value: values.account,errors: [new Error(data.mes)] }
                                });
                            }
                            Modal.warning({
                                title: '保存失败',
                                content: `${data.mes}请返回重新操作`,
                            });
                        }
                    }
                });
            }else{
                message.error(`请按规定填写信息，再提交`,1);
            }
        })
    }
    //获取申请列表  starttime, endtime, product（产品）, umbrellaname（平台）, state, people（负责人）, pagesize, pageindex
    getBannerList() {
        let url=`${config.juseLittleTool}/information/list`;
        $.ajax({
            url: url,
            type: "GET",
            async: true,
            headers: {
                'Authorization': 'Bearer ' + sessionStorage.getItem('token'),
            },
            success: data => {
                console.log(data);
                if (data.code === 200) {
                    const channelList = data.data;
                    console.log(channelList)
                    if (channelList.length > 0) {
                        channelList.forEach((ele, i) => {
                            ele.index = i + 1;
                        });
                        this.setState({
                            channelList,
                        });
                    }else{
                        this.setState({
                            channelList:[],
                            channelcount: 0,
                        });
                    }
                } else {
                    message.error(`${data.mes} 请返回重新操作`, 2);
                }
            }
        });
    }
    //banner详细信息对话框（新增/编辑）
    showBannerModal(values) {
        if(values){
            this.setState({
                record:values,
            })
        }else{
            this.setState({
                record:{},
            })
        }
        if(values){
            this.props.form.setFieldsValue({
                inforname:values.inforname,//收款账户名
                openingbank:values.openingbank,//开户行
                subbranch:values.subbranch,//支行
                account:values.account,//银行卡号
            });
            this.setState({
                visible: true,
                BannerId: values.id,
                createpeople:values.createpeople,
            });
        }else{
            this.setState({
                visible: true,
                BannerId:undefined,
                createpeople:''
            });
        }
    }
    //取消，关闭对话框
    handleCancel() {
        this.props.form.resetFields();
        this.setState({
            visible: false,
            wordCount1:0,
        });
    }
    //删除数据
    deleteData(id){
        Modal.confirm({
            title: '删除',
            content: '温馨提示：删除后不可恢复，是否继续删除？',
            onOk: () => {
                let url=`${config.juseLittleTool}/information/delete`;
                $.ajax({
                    url: url,
                    type: "POST",
                    async: true,
                    headers: {
                        'Authorization': 'Bearer ' + sessionStorage.getItem('token'),
                    },
                    data:{
                        id:id,
                    },
                    success: data => {
                        console.log(data);
                        if (data.code === 200) {
                            message.success('删除成功！',1);
                            this.getBannerList();
                        } else {
                            message.error(`${data.mes} 请返回重新操作`, 2);
                        }
                    }
                });
            }
        });
    }
    render() {
        //费用预览表格
        const data = [
            {
                title: '添加时间',
                dataIndex: 'createtime',
                width: 170,
            },{
                title: '收款账户名',
                dataIndex: 'inforname',
                width: 120,
            },{
                title: '开户行',
                dataIndex: 'openingbank',
                width: 120,
            },{
                title: '支行',
                dataIndex: 'subbranch',
                width: 120,
            },{
                title: '银行卡号',
                dataIndex: 'account',
                width: 200,
            }, {
                title: '添加人',
                width: 100,
                dataIndex: 'createpeople',
                render: text => <span>{text == 1 ? '超级管理员' : text}</span>
            } , {
                title: '操作',
                width: 100,
                render: (text, record) => (
                    <div>
                       <Button  type="primary" onClick={this.showBannerModal.bind(this,record)}>编辑</Button>
                       <Button  type="danger" onClick={this.deleteData.bind(this,record.id)}>删除</Button>
                    </div>
                )
            }
        ];
        const { getFieldDecorator } =this.props.form;
        const formItemLayout = { labelCol: { span: 6 }, wrapperCol: { span: 16 }, };
        const{visible,record,createpeople}=this.state;
        return (
            <div className='goods-label clearfix'>
                {/*面包屑*/}
                < Breadcrumb separator=">" >
                    <Breadcrumb.Item>橘色小工具</Breadcrumb.Item>
                    <Breadcrumb.Item>资料管理</Breadcrumb.Item>
                    <Breadcrumb.Item>资料列表</Breadcrumb.Item>
                </Breadcrumb >
                <div style={{marginTop:'40px'}} className="clearfix">
                   <Button type="primary" style={{marginLeft:'10px'}}  onClick={() => this.showBannerModal()}>新增资料</Button>
                    <div  className='allgoods-table clearfix' style={{marginTop:'40px'}}>
                        <Table
                               rowKey="index"
                               columns={data}
                               dataSource={this.state.channelList}
                               bordered
                               pagination={false}
                        />
                    </div>
                </div>
                <Modal
                    className="banner-modal"
                    title={(JSON.stringify(record)==="{}")?'新增资料':"编辑资料"}
                    visible={visible}
                    okText="确定"
                    cancelText="取消"
                    onOk={this.saveBanner.bind(this)}
                    onCancel={this.handleCancel.bind(this)}
                    maskClosable={false}
                >
                    <Form>
                        <Row>
                            <Col span={24} >
                                <FormItem {...formItemLayout} label=" 收款账户名"  style={{ minHeight: '60px', marginBottom: 0 }}>
                                    {getFieldDecorator('inforname', {
                                        rules: [
                                            { required: true, message: '请输入收款账户名' },
                                            { pattern: /^\S+$/, message: '请不要输入空格'}
                                            ],
                                    })(
                                        <Input placeholder="请输入收款账户名" />
                                    )}
                                </FormItem>
                            </Col>
                        </Row>
                        <Row>
                            <Col span={24} >
                                <FormItem {...formItemLayout} label=" 开户行"  style={{ minHeight: '60px', marginBottom: 0 }}>
                                    {getFieldDecorator('openingbank', {
                                        rules: [{ required: true, message: '请输入开户行' },
                                            { pattern: /^\S+$/, message: '请不要输入空格'}],
                                    })(
                                        <Input placeholder="请输入开户行" />
                                    )}
                                </FormItem>
                            </Col>
                        </Row>
                        <Row>
                            <Col span={24} >
                                <FormItem {...formItemLayout} label=" 支行"  style={{ minHeight: '60px', marginBottom: 0 }}>
                                    {getFieldDecorator('subbranch', {
                                        rules: [{ required: true, message: '请输入支行' },
                                            { pattern: /^\S+$/, message: '请不要输入空格'}],
                                    })(
                                        <Input placeholder="请输入支行" />
                                    )}
                                </FormItem>
                            </Col>
                        </Row>
                        <Row>
                            <Col span={24} >
                                <FormItem {...formItemLayout} label=" 银行卡号"  style={{ minHeight: '60px', marginBottom: 0 }}>
                                    {getFieldDecorator('account', {
                                        rules: [{ required: true, message: '请输入银行卡号' },
                                            { pattern: /^\S+$/, message: '请不要输入空格'}],
                                    })(
                                        <Input placeholder="请输入银行卡号" />
                                    )}
                                </FormItem>
                            </Col>
                        </Row>
                        <p style={{fontSize: '14px',color:'rgba(0, 0, 0, 0.85)',paddingLeft:'40px'}}>添加人：{createpeople==1?'超级管理员':createpeople}</p>
                    </Form>
                </Modal>
            </div>
        )
    }
}
const FileManage = Form.create()(FileManage1);
export default FileManage;